<template>
  <a-drawer destroy-on-close width="500" :title="title" :visible="visible"
            @close="onClose">
    <a-form layout="vertical">
      <a-form-item label="字段名称" name="field_name" v-bind="validateInfos.field_name">
        <a-input placeholder="输入字段名称" v-model:value="modelRef.field_name"/>
      </a-form-item>
      <a-form-item label="字段类型" v-bind="validateInfos.field_type" name="field_type">
        <a-select :options="fieldOptions" placeholder="选择字段类型" :disabled="isEdit"
                  v-model:value="modelRef.field_type" @change="changeField"
        />
      </a-form-item>
      <a-form-item v-if="modelRef.field_type=='singleSelect'||modelRef.field_type=='mutiSelect'"
                   label="下拉选项"
                   v-bind="validateInfos.option" name="option">
        <div class="flex space-between align-center" style="margin-bottom: 5px"
             v-for="(item,index) in modelRef.option">
          <a-input class="flex-1" placeholder="请输入选项" v-model:value="item.value"/>
          <div style="width: 70px">
            <a-button style="width: 30px;" type="link" @click="addOption"
                      v-if="index==modelRef.option.length-1">
              <template #icon>
                <PlusCircleOutlined/>
              </template>
            </a-button>
            <a-button style="width: 30px;" danger type="text" v-if="modelRef.option.length!=1"
                      @click="deleteOption(index)">
              <template #icon>
                <DeleteOutlined/>
              </template>
            </a-button>
          </div>
        </div>
      </a-form-item>
      <a-form-item>
        <template #label>
          <span style="margin-right: 5px">关联项目</span>
          <span style="color: #999;margin-left: 3px">(多选)</span>
          <!--          <a-tooltip>-->
          <!--            <template #title>不选择代表应用于所有项目</template>-->
          <!--            <QuestionCircleOutlined/>-->
          <!--          </a-tooltip>-->
        </template>
        <!--        <a-cascader-->
        <!--            v-model:value="modelRef.build_ids"-->
        <!--            :options="optionsBuild"-->
        <!--            placeholder="请选择"-->
        <!--            @change="buildChange"-->
        <!--            multiple-->
        <!--        />-->
        <a-select
            v-model:value="modelRef.village_id"
            :options="optionsBuild"
            mode="multiple"
            placeholder="请选择项目"
            @change="buildChange"
            :disabled="isEdit"
        ></a-select>
        <div style="color: #999;padding-top: 3px;font-size: 13px">不选择代表应用于所有项目</div>
      </a-form-item>

      <a-form-item label="是否必填">
        <a-switch :checked="(modelRef.is_required==1)?true:false"
                  @change="modelRef.is_required=(modelRef.is_required==1)?0:1"/>
      </a-form-item>
      <a-form-item label="排序" name="sort" v-bind="validateInfos.sort">
        <a-input-number style="width: 100%" placeholder="输入排序值" min="1" max="100"
                        v-model:value="modelRef.sort"/>
      </a-form-item>
    </a-form>
    <div class="drawer-footer">
      <a-space>
        <a-button @click.stop="onClose">取消</a-button>
        <a-button type="primary" @click.stop="save">保存</a-button>
      </a-space>
    </div>
  </a-drawer>
</template>

<script>
import {ref, toRefs, watch, reactive} from "vue";
import {message, Form} from "ant-design-vue";
import {QuestionCircleOutlined, DeleteOutlined, PlusCircleOutlined} from '@ant-design/icons-vue'
import request from '@/common/utils/request'
import _ from "lodash";


const useForm = Form.useForm

export default {
  components: {QuestionCircleOutlined, DeleteOutlined, PlusCircleOutlined},
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    id: {
      type: Number,
      default: 0
    },
    villageId: {
      type: Number,
      default: 0
    }
  },
  setup(props, context) {

    const state = reactive({
      title: "",
      isEdit: false,


    })

    const modelRef = reactive({
      field_name: "",
      sort: 100,
      field_type: undefined,
      is_required: 1,
      option: [],
      village_id: [],
      select_type: 0

    })
    let validateItem = async (_rule, value) => {
      const isRequired = (modelRef.field_type == 'singleSelect' || modelRef.field_type == 'mutiSelect');
      if (!isRequired) {
        return Promise.resolve()
      }
      if (modelRef.option.length > 0) {
        const tempOpt = modelRef.option.filter(item => {
          return item.value.length == 0
        })
        if (tempOpt.length != 0) {
          return Promise.reject()
        }
        return Promise.resolve()
      }
      return Promise.reject()
    };

    const ruleRef = reactive({
      field_name: [{
        required: true,
        message: '请输入字段名称'
      }],
      field_type: [{
        required: true,
        message: '请选择字段类型'
      }],
      option: [{
        required: true,
        message: '请完整输入选项或删除空选项',
        validator: validateItem
      }],
      sort: [{
        required: true,
        message: '请输入排序值'
      }],

    })

    const {resetFields, validate, validateInfos} = useForm(modelRef, ruleRef)

    const onClose = () => {
      context.emit("toClose");
    }

    const buildChange = (value) => {
      // if (value?.length > 0) {
      //   formData.village_id = value[0];
      // }
    };

    const save = () => {

      validate().then(() => {

        const key = modelRef.field_type + _.random(1, 10000)
        const extra = {
          key: key
        }
        if (modelRef.field_type == 'input' || modelRef.field_type == 'textarea') {
          extra.content = ""
        } else if (modelRef.field_type == 'singleSelect') {
          extra.selectOption = ""
        } else if (modelRef.field_type == 'mutiSelect') {
          extra.selectOptions = []
        } else {
          extra.files = []
        }
        if (state.isEdit) {
          // 编辑x
          const params = {
            id: props.id,
            ...modelRef,
            extra: extra
          }
          request.put("/org", "/business/clueField/editClueField", params).then(res => {
            console.log(res)

            message.success("操作成功")
            context.emit("onSuccess")
          })
        } else {
          // 新增
          const params = {
            ...modelRef,
            extra: extra
          }
          request.post("/org", "/business/clueField/addClueField", params).then(res => {
            console.log(res)

            message.success("操作成功")
            context.emit("onSuccess")
          })
        }
      })
    }

    const changeField = (e) => {
      console.log(e)
      if (e == 'mutiSelect' || e == 'singleSelect') {
        modelRef.option = [{value: ""}]
        modelRef.select_type = e == 'mutiSelect' ? 1 : 0
      } else {
        modelRef.option = []
      }


    }
    const addOption = (index) => {
      modelRef.option.push({value: ""})
    }
    const deleteOption = (index) => {
      modelRef.option.splice(index, 1)
    }

    const getDetail = () => {
      request.get("/org", "/business/clueField/clueFieldDetail", {id: props.id}).then(res => {
        console.log(res)
        const detail = res.data
        modelRef.field_name = detail?.field_name;
        modelRef.field_type = detail.field_type;
        modelRef.is_required = detail.is_required;
        modelRef.option = detail.option;
        modelRef.sort = detail.sort;

      })


    }
    // 意向楼宇
    const optionsBuild = ref([]);
    const getBuildList = () => {
      request
          .get("/org", "/build/villageAndBuildList", {checked: 1})
          .then((res) => {
            const vList = res.villageList.map((item) => {
              return {
                label: item.name,
                value: item.id,
                children: item.buildList.map((childItem) => {
                  return {
                    label: childItem.build_name,
                    value: childItem.id,
                  };
                }),
              };
            });
            optionsBuild.value = vList;
          });
    };

    const init = () => {
      if (props.id != 0) {
        getDetail()
      }
      if (props.villageId) {
        modelRef.village_id = [props.villageId];
      }
      state.title = props.id == 0 ? "新增字段" : "编辑字段";
      state.isEdit = props.id == 0 ? false : true;
      getBuildList();
    }

    watch(() => props.visible, (value) => {
      if (value) {
        init();
      } else {
        resetFields();
      }
    })

    const fieldOptions = [
      {label: "单行文本框", value: "input"},
      {label: "多行文本框", value: "textarea"},
      {label: "单选下拉框", value: "singleSelect"},
      {label: "多选下拉框", value: "mutiSelect"},
      {label: "图片", value: "image"},
      {label: "附件", value: "file"},
    ]

    return {
      ...toRefs(state),
      onClose,
      validateInfos,
      modelRef,
      save,
      fieldOptions,
      optionsBuild,
      buildChange,
      deleteOption,
      addOption,
      changeField


    }
  }
}
</script>

<style lang="less" scoped>

</style>